package core

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"time"
	"xinduobang/stock/common"
	"xinduobang/stock/core/log"
)

var (
	mysqlFactory *sql.DB
)

func initMysql(mysqlConfig *common.MysqlConfig) {

	dataSoureName := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", mysqlConfig.User, mysqlConfig.Password,
		mysqlConfig.Host, mysqlConfig.Port, mysqlConfig.DbName)
	var err error
	mysqlFactory, err = sql.Open("mysql", dataSoureName)
	if err != nil {
		log.Error("mysql connect error:", err)
		return
	}

	// 连接池设置
	maxOpenConns, maxIdleConns := 30, 10
	if mysqlConfig.MaxOpenConns > 0 {
		maxOpenConns = mysqlConfig.MaxOpenConns
	}
	if mysqlConfig.MaxIdleConns > 0 {
		maxIdleConns = mysqlConfig.MaxIdleConns
	}

	mysqlFactory.SetMaxOpenConns(maxOpenConns)
	mysqlFactory.SetMaxIdleConns(maxIdleConns)
	mysqlFactory.SetConnMaxIdleTime(1800 * time.Second)
	mysqlFactory.SetConnMaxLifetime(3 * 3600 * time.Second)

	// 尝试连接数据库
	err = mysqlFactory.Ping()
	if err != nil {
		log.Panic("Failed to ping the database:", err)
		return
	}
	log.Infof("Connected to MySQL database %v:%v!", mysqlConfig.Host, mysqlConfig.Port)

	//db.Exec()
	//db.Name()
	//go abc()
}

func Mysql() *sql.DB {
	return mysqlFactory
}

func GetMysql(dbName string) (*sql.DB, error) {
	if mysqlFactory == nil {
		return nil, fmt.Errorf("mysqlFactory is nil")
	}

	_, err := mysqlFactory.Exec(fmt.Sprintf("use `%s`", dbName))
	if err != nil {
		err1 := fmt.Errorf("mysql use database error: %v, dbName: %v", err, dbName)
		log.Error("mysql use database error:", err, "dbName:", dbName)
		return nil, err1
	}

	return mysqlFactory, nil
}

// close Mysql
func CloseMysql(uuidStr string) {
	log.Infof("uuid:%s mysql close ...", uuidStr)
	err := mysqlFactory.Close()
	if err != nil {
		log.Errorf("uuid:%s mysql close error:", uuidStr, err)
		return
	}
}
